package com.qssoft.cqry.synchdb.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.qssoft.cqry.synchdb.adapter.RedisMessageAdapter;
import com.qssoft.cqry.synchdb.adapter.SynchDbAdapter;
import com.qssoft.cqry.synchdb.vo.MysqlBinlogVo;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * @author liju.z
 */
@Slf4j
@AllArgsConstructor
public class RedisMessageHandler implements RedisMessageAdapter {

    private final SynchDbAdapter synchDbAdapter;

    private final JdbcTemplate jdbcTemplate;

    private final RedisSynchHandler redisSynchHandler;

    @SneakyThrows
    @Override
    public void getMessage(String threadName) {
        //加线程锁
        List<MysqlBinlogVo> mysqlBinlogVoList = redisSynchHandler.getSynchData();
        if (CollectionUtil.isEmpty(mysqlBinlogVoList)) {
            return;
        }
        log.info("获取到同步获取消息...{}", mysqlBinlogVoList);
        //处理db数据
        try {
            mysqlBinlogVoList.forEach(synchData -> {
                /**
                 * 1、执行完成后删除对应的缓存数据
                 * 2、当发生错误后，对错误类型做缓存操作
                 * 3、session一定要关闭
                 */
                try {
                    boolean deleteRedisMessage = synchDbAdapter.handler(jdbcTemplate, synchData);
                    if (deleteRedisMessage) {
                        redisSynchHandler.deleteSynchData(synchData);
                    }
                } catch (Exception ex) {
//                    handlerException(ex, synchData);
                    throw ex;
                }
            });
        } catch (Exception ex) {
            log.error("同步server端数据出错...{}", ex);
        } finally {
//            connection.close();
        }
    }

    /**
     * 异常处理
     *
     * @param ex
     * @param synchData
     */
//    private void handlerException(Exception ex, SynchDataVo synchData) {
//        //主键错误需要删除
//        if (ex instanceof SQLIntegrityConstraintViolationException) {
//            redisSynchHandler.deleteSynchData(synchData);
//        }
////        //自定义错误删除缓存
////        else if (ex instanceof BaseException) {
////            redisSynchHandler.deleteSynchData(synchData);
////        }
//    }
}
